using System;
using System.IO;
using System.Text;
using System.Xml;

namespace MMXSaveGameConverter
{
    internal sealed class SaveFileMeta
    {
        public readonly string Name;

        public SaveFileMeta(string name)
        {
            Name = name;
        }

        public static SaveFileMeta FromSave(Stream saveInput)
        {
            BinaryReader br = new BinaryReader(saveInput, Encoding.Unicode);

            int length = br.ReadInt32();
            int version = br.ReadInt32();
            if (version != 0)
                throw new FileFormatException();

            byte[] data = br.ReadBytes(length - 4);
            string name = Encoding.Unicode.GetString(data);

            return new SaveFileMeta(name.TrimEnd('\0'));
        }

        public static SaveFileMeta FromXml(XmlDocument xmlDocument)
        {
            XmlElement node = xmlDocument["SavedGame"];
            if (node == null)
                throw new Exception("SaveGame node is not found.");

            XmlAttribute attribute = node.Attributes["Name"];
            return attribute == null ? new SaveFileMeta(string.Empty) : new SaveFileMeta(attribute.Value);
        }

        public void ToSave(Stream saveOutput)
        {
            byte[] buff = new byte[0x0224 + 4];
            BitConverter.GetBytes(0x0224).CopyTo(buff, 0);
            Encoding.Unicode.GetBytes(Name, 0, Name.Length, buff, 8);
            saveOutput.Write(buff, 0, buff.Length);
        }

        public void ToXml(XmlDocument xmlDocument)
        {
            XmlElement node = xmlDocument["SavedGame"];
            if (node == null)
                throw new Exception("SaveGame node is not found.");

            node.Attributes.Append(xmlDocument.CreateAttribute("Name")).Value = Name;
        }
    }
}